from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from rest_framework import status
from .models import WallPost, PostLike, PostComment

class WallTests(TestCase):
    def setUp(self):
        # 创建测试用户
        self.client = APIClient()
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123'
        )
        self.client.force_authenticate(user=self.user)
        
        # 创建测试帖子
        self.post = WallPost.objects.create(
            user=self.user,
            content='测试帖子内容',
            study_time=60
        )

    def test_create_post(self):
        """测试创建帖子"""
        response = self.client.post('/api/wall/posts/', {
            'content': '新帖子内容',
            'study_time': 30
        })
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(WallPost.objects.count(), 2)

    def test_like_post(self):
        """测试点赞帖子"""
        response = self.client.post(f'/api/wall/posts/{self.post.id}/like/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(PostLike.objects.count(), 1)
        self.assertEqual(
            WallPost.objects.get(id=self.post.id).likes_count,
            1
        )

    def test_create_comment(self):
        """测试创建评论"""
        response = self.client.post(
            f'/api/wall/posts/{self.post.id}/comments/',
            {'content': '测试评论内容'}
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(PostComment.objects.count(), 1)
        self.assertEqual(
            WallPost.objects.get(id=self.post.id).comments_count,
            1
        )

    def test_delete_post(self):
        """测试删除帖子"""
        response = self.client.delete(f'/api/wall/posts/{self.post.id}/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(WallPost.objects.count(), 0)

    def test_get_post_comments(self):
        """测试获取帖子评论"""
        # 创建测试评论
        PostComment.objects.create(
            post=self.post,
            user=self.user,
            content='测试评论'
        )
        
        response = self.client.get(f'/api/wall/posts/{self.post.id}/comments/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)
